#include "NetCal.hpp"
#include "Socket.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " server_ip server_port" << std::endl;
}

void GetDataFromStdin(int *x, int *y, char *oper)
{
    std::cout << "Please Enter x: ";
    std::cin >> *x;
    std::cout << "Please Enter y: ";
    std::cin >> *y;
    std::cout << "Please Enter oper: ";
    std::cin >> *oper;
}

// ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    // 进行命名行参数检测，并获取服务器 ip 和 port 
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 2. 创建客户端套接字并连接服务器
    std::shared_ptr<Socket> client = std::make_unique<TcpSocket>();
    client->BuildTcpClientSocketMethod();
    if (client->Connect(server_ip, server_port) < 0)
    {
        // 连接失败
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    // 3. 从标准输入获取数据并发送给服务器并接收应答显示结果
    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    std::string resp_buffer;
    while(true)
    {
        // 3.1. 从标准输入中获取数据
        int x, y;
        char oper;
        GetDataFromStdin(&x, &y, &oper);

        // 3.2. 构建一个请求
        Request req(x, y, oper);
        std::string req_json_str = req.Serialize();
        std::string req_str = protocol->Encode(req_json_str);

        // 3.3. 发送请求
        client->Send(req_str);

        // 3.4. 获取应答
        Response resp;
        bool res = protocol->GetResponse(client, resp_buffer, &resp);
        if (res == false)
            break;

        // 3.5. 显示结果
        resp.ShowResult();
    }

    client->Close();
    return 0;
}